# -*-coding:utf-8-*-
"""
通过matplotlib 和Seaborn echart numpy生成图片
"""
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import mplfinance as mpf
from sqlalchemy import create_engine
from matplotlib.pylab import date2num
import os
from datetime import date
import shutil
# 解决字体问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 解决mplfinance绘制输出中文乱码
s = mpf.make_mpf_style(base_mpf_style='charles', rc={'font.family': 'SimHei'})


class HanderZnzView:

    def __init__(self):
        pass

    def _run(self):
        self._mkdir_outfile_dirs()  # 创建文件夹
        self._del_outfile_dirs()

    def _create_img_by_index0_pddata(self, pddata):
        """
        根据DF数据结构生成图表图片
        返回图片路径
        生成0号指数图表数据
        """

        # 日期正序
        pddata = pddata.sort_values(by='date', ascending=True)
        # 获取结束日期 和开始日期
        date_str = pddata.iloc[0]['date']+'_'+pddata.iloc[-1]['date']
        # print(date_str)
        fig_name = self.index0_path_ + '/index0_'+date_str+'.jpg'  # 根据执行文件的相对路径
        # 删除其他列
        pddata.drop('tq_0', axis=1, inplace=True)
        # 修改列名
        pddata.rename(columns={'date': 'datetime', 'open_0': 'Open',
                               'close_0': 'Close', 'high_0': 'High', 'low_0': 'Low'}, inplace=True)
        # 修改数据为亿元单位:
        pddata['Open'] = pddata['Open']/100000000
        pddata['Close'] = pddata['Close']/100000000
        pddata['High'] = pddata['High']/100000000
        pddata['Low'] = pddata['Low']/100000000
        # 调整列顺序,同时只显示 调整的列名
        pddata = pddata[['datetime', 'Open', 'High', 'Low', 'Close']]
        # print(pddata.head(1))
        # 时间列为索引
        pddata['datetime'] = pd.to_datetime(pddata['datetime'])
        pddata.set_index("datetime", inplace=True)

        # print(pddata.head(1))
        # 设置附加曲线
        index_close = pddata['Close']
        add_plot = [mpf.make_addplot(index_close,
                                     scatter=False,
                                     markersize=2,
                                     marker='^',
                                     color='y')]
        # 创建基础蜡烛图
        # pddata 的列顺序为：Open,High,Low,Close
        mpf.plot(
            pddata,
            type='candle',
            title='0号指标及收盘曲线'+date_str,
            ylabel='0号指标价格(亿元)',  # y轴标签
            style=s,  # 设置样式
            figratio=(16, 9),  # 设置图表大小
            savefig=fig_name,  # 保存文件路径
            figscale=1.5,  # 图片放大150%
            datetime_format='%Y-%m-%d',  # 日期格式
            addplot=add_plot  # 添加附加指标
        )

        # print(fig_name)

    def _create_img_by_index0b_pddata(self, pddata):
        """
        0B指数 图
        """

        # 日期正序
        pddata = pddata.sort_values(by='date', ascending=True)
        # 获取结束日期 和开始日期
        date_str = pddata.iloc[0]['date']+'_'+pddata.iloc[-1]['date']
        # print(date_str)
        fig_name = self.index0b_path_ + '/index0b_'+date_str+'.jpg'  # 根据执行文件的相对路径
        pddata['tq_0'] = pddata['tq_0']/100000000  # 流通盘 （亿股）
        # 时间列为索引
        pddata['date'] = pd.to_datetime(pddata['date'])
        # pddata.set_index("date", inplace=True)
        # 删除其他列
        pddata.drop('close_0', axis=1, inplace=True)
        pddata.drop('open_0', axis=1, inplace=True)
        pddata.drop('high_0', axis=1, inplace=True)
        pddata.drop('low_0', axis=1, inplace=True)
        # print(pddata)
        pddata.plot(
            x='date',
            y='tq_0',
            title='index0B--'+date_str,
            kind='line',  # 折线
            grid=True,
            figsize=(16, 9),  # 图步尺寸
            fontsize=15,  # 轴上字体大小
            xlabel='日期',
            ylabel='流通盘（亿股）'
        )
        plt.savefig(fig_name)  # 保存图片

    def _create_img_by_index0a_pddata(self, pddata):
        """
        0A指数图
        """

        # 日期正序
        pddata = pddata.sort_values(by='date', ascending=True)
        # 获取结束日期 和开始日期
        date_str = pddata.iloc[0]['date']+'_'+pddata.iloc[-1]['date']
        # print(date_str)
        fig_name = self.index0a_path_ + '/index0a_'+date_str+'.jpg'  # 根据执行文件的相对路径
        # 删除其他列
        pddata.drop('tq_0', axis=1, inplace=True)
        # 修改列名
        pddata.rename(columns={'date': 'datetime', 'open_0A': 'Open',
                               'close_0A': 'Close', 'high_0A': 'High', 'low_0A': 'Low'}, inplace=True)

        # 调整列顺序
        pddata = pddata[['datetime', 'Open', 'High', 'Low', 'Close']]
        # 时间列为索引
        pddata['datetime'] = pd.to_datetime(pddata['datetime'])
        pddata.set_index("datetime", inplace=True)

        # print(pddata.head())
        # 调整列顺序

        # 设置附加曲线
        index_close = pddata['Close']
        add_plot = [mpf.make_addplot(index_close,
                                     scatter=False,
                                     markersize=2,
                                     marker='^',
                                     color='y')]
        # 创建基础蜡烛图
        # pddata 的列顺序为：Open,High,Low,Close

        mpf.plot(
            pddata,
            type='candle',
            title='0A指标及收盘曲线'+date_str,
            ylabel='0A指数价格(元)',  # y轴标签
            style=s,  # 设置样式
            figratio=(16, 9),  # 设置图表大小
            savefig=fig_name,  # 保存文件路径
            figscale=1.5,  # 图片放大150%
            datetime_format='%Y-%m-%d',  # 日期格式
            addplot=add_plot  # 添加附加曲线

        )

    def create_sql_con(self, cfg):
        self.con = create_engine(
            'mysql+pymysql://'+cfg.CONFIG['db']['default']['username']+':'+cfg.CONFIG['db']['default']['pwd']+'@'+cfg.CONFIG['db']['default']['host']+':'+cfg.CONFIG['db']['default']['port']+'/'+cfg.CONFIG['db']['default']['dbname']+'?charset=utf8')

    def get_data_from_sql(self, table_name=None, pages=1, num_=7, desc=True):
        """
        获取分页数据
        """
        index_ = (pages-1)*num_
        num_ = num_
        if desc:
            desc_ = "desc"
        else:
            desc_ = "asc"

        sql_ = "select * from `{0}`  order by date {1} limit {2},{3}".format(
            table_name, desc_, index_, num_)
        data = pd.read_sql(sql_, self.con)
        return data

    def get_data_count(self, table_name=None):
        """
        获取总数据
        """
        sql_ = "select count(`date`) from `{0}`".format(table_name)
        data = pd.read_sql(sql_, self.con)
        return data

    def _del_outfile_dirs(self):
        """
        删除输出文件夹下日期文件夹-非当日文件夹
        待当日文件夹创建后删除其他的
        """
        # 根据日期创建文件夹
        path_ = date.today().strftime('%Y%m%d')
        index0_path_ = './outfile/index0/'
        index0b_path_ = './outfile/index0b/'
        index0a_path_ = './outfile/index0a/'
        for root, dir, _ in os.walk(index0_path_):
            if dir:
                for i in dir:
                    if i != path_:
                        shutil.rmtree(os.path.join(root, i))

        for root, dir, _ in os.walk(index0b_path_):
            if dir:
                for i in dir:
                    if i != path_:
                        shutil.rmtree(os.path.join(root, i))
        for root, dir, _ in os.walk(index0a_path_):
            if dir:
                for i in dir:
                    if i != path_:
                        shutil.rmtree(os.path.join(root, i))

    def _mkdir_outfile_dirs(self):
        """
        在输出文件夹下创建当日文件夹，当日产生的数据存放在当日文件夹下
        """
        # 根据日期创建文件夹
        path_ = date.today().strftime('%Y%m%d')

        self.index0_path_ = './outfile/index0/'+path_
        if not os.path.exists(self.index0_path_):
            os.mkdir(self.index0_path_)  # Todo  unix系统下有文件夹权限问题
        else:
            # 强制删除 然后创建 ,目的是如果文件夹下的文件正在使用则正常删除不了
            shutil.rmtree(self.index0_path_)
            os.mkdir(self.index0_path_)

        self.index0b_path_ = './outfile/index0b/'+path_
        if not os.path.exists(self.index0b_path_):
            os.mkdir(self.index0b_path_)  # Todo  unix系统下有文件夹权限问题
        else:
            # 强制删除 然后创建 ,目的是如果文件夹下的文件正在使用则正常删除不了
            shutil.rmtree(self.index0b_path_)
            os.mkdir(self.index0b_path_)

        self.index0a_path_ = './outfile/index0a/'+path_
        if not os.path.exists(self.index0a_path_):
            os.mkdir(self.index0a_path_)  # Todo  unix系统下有文件夹权限问题
        else:
            # 强制删除 然后创建 ,目的是如果文件夹下的文件正在使用则正常删除不了
            shutil.rmtree(self.index0a_path_)
            os.mkdir(self.index0a_path_)
